<template>
  <div class>
    <el-row :gutter="20">
      <el-col :span="6">
        <!-- <el-card> -->
        <el-tree style="min-height:calc(100vh - 140px);" highlight-current @node-click="handleNodeClick" :props="props"
          :data="data" node-key="id"></el-tree>
      </el-col>
      <el-col :span="18" style="background:#fff;padding:10px;min-height:calc(100vh - 140px);">
        <div class="btns">
          <el-dropdown class="btns" @command="handleCommand">
            <el-button size="mini" type="primary">
              增加
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="部门" @click="addItem">部门</el-dropdown-item>
              <el-dropdown-item command="职员" @click="showDialog">职员</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="mini" @click="editItem">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteItem">删除</el-button>
        </div>
        <el-form :model="form" :rules="rules" ref="form" label-width="170px" inline size="mini">
          <el-row>
            <el-form-item label="上级部门名称" prop="superName">
              <el-input v-model="form.superName" disabled style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="本级部门编号" v-show="!isAdd" prop="organCode">
              <el-input v-model="form.organCode" disabled style="width:200px"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="启用状态" prop="status">
              <el-select v-model="form.status" :disabled="justshow" style="width:200px">
                <el-option label="启用" :value="1"></el-option>
                <el-option label="停用" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="本级部门名称" prop="organName">
              <el-input v-model="form.organName" :disabled="justshow" style="width:200px"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="本级部门简码" prop="shortName">
              <el-input v-model="form.shortName" :disabled="justshow" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="显示顺序" prop="displayOrder">
              <el-input v-model="form.displayOrder" :disabled="justshow" style="width:200px"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="部门类型" prop="organType">
              <el-select v-model="form.organType" :disabled="justshow" style="width:200px;">
                <el-option label="公司" value="1"></el-option>
                <el-option label="部门" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否独立建账" prop="dependentAccount">
              <el-select v-model="form.dependentAccount" :disabled="justshow" style="width:200px">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-row>

          <el-form-item label="节点位置" v-show="isAdd">
            <el-radio-group v-model="nodeType" @change="nodeTypeChange">
              <el-radio label="1">兄弟节点</el-radio>
              <el-radio label="2">子节点</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="btns" v-show="!justshow">
            <el-button @click="cancle">取 消</el-button>
            <el-button type="primary" @click="ok">确 定</el-button>
          </div>
        </el-form>
        <!--组织机构中的用户信息-->
        <el-table stripe :data="tableData" border style="width: 100%">
          <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
          <!-- <el-table-column prop="organCode" width="300" align="center" label="部门编号"></el-table-column> -->
          <el-table-column prop="realName" width="120" align="center" label="职员姓名"></el-table-column>
          <el-table-column prop="authStatus" width="120" align="center" label="是否授权" :formatter="authStatusFilter">
          </el-table-column>
          <el-table-column prop="organName" align="center" width="120" label="部门名称"></el-table-column>
          <el-table-column prop="username" width="120" align="center" label="职员账号"></el-table-column>
          <el-table-column prop="sex" align="center" label="性别"></el-table-column>
          <el-table-column prop="telephone" width="120" align="center" label="固定电话"></el-table-column>
          <el-table-column prop="mobile" width="120" align="center" label="移动电话"></el-table-column>
          <el-table-column prop="createTime" width="180" align="center" label="创建时间"></el-table-column>
          <el-table-column label="操作" width="180px" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleSeeMore(scope.row)">详情</el-button>
              <el-button size="mini"  type="success" @click="scope.row.authStatus==0?authToUser(scope.row):clearAuthToUser(scope.row)">{{`${scope.row.authStatus==0?"授权":"取消"}`}}</el-button>
              <el-button size="mini" type="danger" @click="deleteOrganUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-card style="text-align:right;">
          <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="currentPage"
            :page-sizes="[ 10, 20,30, 40]" :page-size="pageSize" background layout="total, sizes, prev, pager, next"
            :total="total"></el-pagination>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="所有用户" width="60%" :visible.sync="dialogAllUser">
      <users ref="users" v-bind:organId="organId" />
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="dialogAllUser = false">取消</el-button>
        <el-button size="medium" type="success" plain @click="dialogFileShow">保存</el-button>
      </span>
    </el-dialog>
    <!-- ---------------------------------------------------------浏览用户弹出框 -->
    <el-dialog title="用户详情" :visible.sync="dialogUser" width="70%">
      <searchUser ref="searchUser"></searchUser>
    </el-dialog>
    <el-dialog title="上传附件" width="40%" :visible.sync="dialogFile">
      <el-form :model="fileForm" label-width="80px">
        <el-form-item label="备注" width="100%">
          <el-input v-model="fileForm.remark" placeholder="请输入说明" type="textarea" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload class="upload-demo" :action="upUrl" :on-success="handleSuceess" :before-remove="beforeRemove"
            multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件编码">
          <el-input v-model="fileForm.fileHashCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文件名称">
          <el-input v-model="fileForm.fileName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="dialogFile = false">取消</el-button>
        <el-button size="medium" type="success" plain @click="saveOrganUser">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { getMenuList1 } from "@/functions/menuList";
  import { getUserListByRoleId } from "@/pages/auth/qxgl/function";
  import users from "@/pages/auth/jggl/component/organ-user.vue";
  import searchUser from "@/pages/auth/jggl/component/searchUserById.vue";
  import {
    getList,
    deleteItem,
    addItem,
    addItem1,
    editItem,
    // getUserByUserId,
    getUserByOrganCode
  } from "./organ";

  export default {
    components: {
      users,
      searchUser
    },
    data() {
      return {
        fileList: [],
        upUrl:
          this.baseURL +
          "/api/file/upload?Auth-User-Token=" +
          sessionStorage.getItem("token"),
        total: 0,
        pageSize: 10,
        currentPage: 1,
        fileForm: {
          remark: "",
          fileHashCode: "",
          fileName: ""
        },
        dialogFile: false,
        nodeType: "1",
        organId: "",
        dialogUser: false,
        justshow: true,
        isAdd: false,
        dialogAllUser: false,
        dialogFormVisible: false,
        tableData: [],
        // editForm: {
        //   realName: ""
        // },
        options: [],
        cascaderProps: {
          value: "organCode",
          label: "organName",
          children: "children"
        },
        form: {
          id: "",
          parentId: "",
          organCode: "",
          shortName: "",
          organName: "",
          organType: "",
          address: "",
          nodeType: "1",
          master: "",
          linkMan: "",
          linkpHone: "",
          postCode: "",
          remark: "",
          status: "",
          displayOrder: "",
          dependentAccount: "",
          superName: "",
          createUserId: "",
          createUserName: "",
          // createTime: "",
          // updateTime: "",
          nodeKey: ""
        },
        rules: {
          // id: [
          //   { required: true, message: "机构ID不能为空!", trigger: "blur" },
          // ],
          parentId: [
            { required: true, message: "父级ID不能为空！", trigger: "blur" }
          ],
          // organCode: [
          //   { required: true, message: "机构编码不能为空", trigger: "blur" }
          // ],

          shortName: [
            { required: true, message: "机构简称不能为空！", trigger: "blur" }
          ],
          organName: [
            { required: true, message: "机构全称不能为空！", trigger: "blur" }
          ],
          organType: [
            { required: true, message: "机构类型不能为空！", trigger: "blur" }
          ],
          status: [
            {
              required: true,
              type: "number",
              message: "状态不能为空！",
              trigger: "blur"
            }
          ]
        },
        chackedNode: {},
        data: [],
        props: {
          label: "organName",
          children: "children"
        }
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      authStatusFilter(row, column, cellValue){
        if (cellValue == 0) {
          return "否";
        }
        if (cellValue == 1) {
          return "是";
        }
      },
      handleSuceess(response, file, fileList) {
        this.fileForm.fileHashCode = response.retBody.fileHash;
        this.fileForm.fileName = file.name;
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${
          files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        );
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      sizeChange(n) {
        this.pageSize = n;
        this.init();
      },
      currentChange(n) {
        this.currentPage = n;
        this.init();
      },
      clearAuthToUser(row){
        let user = JSON.parse(sessionStorage.getItem("user"));
        let params = {
          id:row.userOrganId,
          changeUserId: user.id,
          authStatus:'0'
        };
          this.$api.formPost("/api/auth/sysUserOrgan/doModById", params).then(res => {
            if (res.retHead.code == "0000000") {
              this.$message({
                type: "success",
                message: "取消成功!"
              });
              this.getUsers(this.chackedNode.id);
              this.dialogFile = false;
              this.dialogAllUser = false;
            } else {
              this.$message({
                type: "error",
                message: res.retHead.message
              });
            }
          });
      },
      authToUser(row){
        let user = JSON.parse(sessionStorage.getItem("user"));
        let params = {
          id:row.userOrganId,
          changeUserId: user.id,
          authStatus:'1'
        };
          this.$api.formPost("/api/auth/sysUserOrgan/doModById", params).then(res => {
            if (res.retHead.code == "0000000") {
              this.$message({
                type: "success",
                message: "授权成功!"
              });
              this.getUsers(this.chackedNode.id);
              this.dialogFile = false;
              this.dialogAllUser = false;
            } else {
              this.$message({
                type: "error",
                message: res.retHead.message
              });
            }
          });
      },
      deleteOrganUser(row) {
        let user = JSON.parse(sessionStorage.getItem("user"));
        let params = {
          userId: row.id,
          organId: this.chackedNode.id,
          changeUserId: user.id
        };
        this.$confirm("此操作将永久删除该条记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            //删除
            this.$api
              .formPost("/api/auth/sysUserOrgan/deleteByUserIdAndOrganId", params)
              .then(res => {
                if (res.retHead.code == "0000000") {
                  // this.init();
                  this.getUsers(this.chackedNode.id);
                  this.$message({
                    type: "success",
                    message: "删除成功!"
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: res.retHead.message
                  });
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      dialogFileShow() {
        // this.fileForm = {};
        this.fileForm.fileHashCode = "";
        this.fileForm.remark = "";
        this.fileForm.fileName = "";
        this.fileList = [];
        this.$nextTick(() => {
          if (
            !this.$refs.users.selections ||
            this.$refs.users.selections.length == 0
          ) {
            this.$message.error("请先选取一个用户！");
            return false;
          }
          this.dialogFile = true;

        });
      },
      saveOrganUser() {
        this.$nextTick(() => {
          let user = JSON.parse(sessionStorage.getItem("user"));
          let params = {
            userList: this.$refs.users.selections,
            organId: this.chackedNode.id,
            organCode: this.chackedNode.organCode,
            organName: this.chackedNode.organName,
            changeUserId: user.id,
            remark: this.fileForm.remark,
            fileHashCode: this.fileForm.fileHashCode,
            fileName: this.fileForm.fileName
          };
          this.$api.post("/api/auth/sysUserOrgan/doSave", params).then(res => {
            if (res.retHead.code == "0000000") {
              this.$message({
                type: "success",
                message: "保存成功!"
              });
              this.getUsers(this.chackedNode.id);
              this.dialogFile = false;
              this.dialogAllUser = false;
            } else {
              this.$message({
                type: "error",
                message: res.retHead.message
              });
            }
          });
        });
      },
      handleCommand(v) {
        if (v == "部门") {
          this.addItem();
        } else if (v == "职员") {
          if (this.rule1()) {
            this.showDialog();
          }
        }
      },
      showDialog() {
        this.dialogAllUser = true;
        this.organId = this.chackedNode.id;
        this.$nextTick(() => {
          this.$refs.users.init();
        });
      },
      nodeTypeChange(v) {
        if (v == 1) {
          this.form.superName = this.chackedNode.superName;
        } else if (v == 2) {
          this.form.superName = this.chackedNode.organName;
        }
      },
      handleSeeMore(row) {
        this.dialogUser = true;
        let id = row.id;
        this.userId = id;
        this.$nextTick(() => {
          this.$refs.searchUser.init(this.userId);
        });
      },

      init() {
        getList().then(res => {
          if (res.retHead.code == "0000000") {
            this.data = res.retBody;
          }
        });
        this.chackedNode = {};
      },
      handleNodeClick(v) {
        this.tableData = [];
        this.justshow = true;
        this.isAdd = false;
        this.chackedNode = v;
        this.getUsers(v.id);
        for (let key in this.form) {
          this.form[key] = this.chackedNode[key];
        }
      },
      cancle() {
        this.justshow = true;
        for (let key in this.form) {
          this.form[key] = this.chackedNode[key];
        }
      },
      getUsers(v) {
        let params = {
          organId: v,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        };
        this.$api
          .formPost("/api/auth/sysuser/doGetOrganUserListByUserOrganId", params)
          .then(res => {
            if (res.retHead.code == "0000000") {
              this.tableData = res.retBody.list;
              // console.log(res.retBody.list);
              this.total = res.retBody.total;
              this.currentPage = res.retBody.pageNum;
            } else {
              this.$message({
                type: "error",
                message: res.retHead.message
              });
            }
          });
      },
      rule1() {
        if (!this.chackedNode.id) {
          this.$message.error("请先选取一个机构！");
          return false;
        } else {
          return true;
        }
      },
      ok() {
        if (this.isAdd) {
          this.handleAdd();
        } else {
          this.handleEdit();
        }
      },
      handleAdd() {
        this.form.nodeType = this.nodeType;
        if (this.form.nodeType == 1) {
          this.form.parentId = this.chackedNode.parentId;
        } else {
          this.form.parentId = this.chackedNode.id;
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            addItem(this.form).then(res => {
              if (res.retHead.code == "0000000") {
                this.$message.success("操作成功！");
                this.init();
              } else {
                this.$message.error("操作失败！");
              }
              this.justshow = true;
              this.isAdd = false;
            });
          }
        });
      },
      handleEdit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            editItem(this.form).then(res => {
              if (res.retHead.code == "0000000") {
                this.init();
                this.$message.success("操作成功！");
              } else {
                this.$message.error("操作失败！");
              }
              this.justshow = true;
            });
          }
        });
      },
      deleteItem() {
        if (this.rule1()) {
          let params = {
            //根据id删除
            id: this.chackedNode.id
          };
          this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //删除
            deleteItem(params).then(res => {
              if (res.retHead.code == "0000000") {
                this.$message.success("删除成功！");
                this.init();
              } else {
                this.$message.error(res.retHead.message);
              }
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }
      },
      addItem() {
        this.nodeType = "1";
        if (this.rule1()) {
          this.justshow = false;
          this.isAdd = true;
          for (let key in this.form) {
            this.form[key] = "";
          }
          this.form.superName = this.chackedNode.superName;
        }
      },
      editItem() {
        if (this.rule1()) {
          this.isAdd = false;
          this.justshow = false;
          for (let key in this.chackedNode) {
            this.form[key] = this.chackedNode[key];
          }
        }
      }
    },
    created() { }
  };
</script>
<style lang="scss" scoped>
  .btns {
    margin-bottom: 10px;
    text-align: left;
  }

  .table {
    display: table;
    width: 100%;
    border: 1px solid #ccc;
    border-bottom: none;
    border-right: none;

    .row {
      display: table-row;

      .item {
        padding: 10px;
        display: table-cell;
        border: 1px solid #ccc;
        border-top: none;
        border-left: none;

        .lable {
          width: 100px;
          display: inline-block;
          font-weight: 700;
        }

        .lable:after {
          content: ":";
        }

        .value {
          display: inline-block;
        }
      }
    }
  }
</style>